package dispatcher.group.gui.floor.state;

import state.Globals;
import state.group.ElevatorStruct;
import state.group.HallCall;
import state.group.events.HallCallEvent;

/**
 * This class contains the information for each floor
 * @author Caleb
 *
 */
public class FloorStruct {

	private byte floor;
	private boolean isUpPressed;
	private boolean isDownPressed;
	
	
	public byte elevatorToService[];
	
	private static final int DEFAULT_MAX_ELEVATORS = 2;
	
	/**
	 * The main constructor
	 * @param floorId The floor ID this struct is associated with
	 */
	public FloorStruct(byte floorId){
		this.floor = floorId;
		resetHall();
	}
	
	/**
	 * This method will reset the struct to the default information
	 */
	public void resetHall(){
		this.isDownPressed = false;
		this.isUpPressed = false;
		
		this.elevatorToService = new byte[DEFAULT_MAX_ELEVATORS];
		for(int i = 0; i < DEFAULT_MAX_ELEVATORS; i++){
			this.elevatorToService[i] = (byte) 0xFF;
		}
	}
	
	/**
	 * This method will update the struct using a HallCall object
	 * @param call The hall call made at the floor
	 * @param elevator The elevator that is servicing the hall call
	 * @param isCompleted The boolean if the floor is still waiting for an elevator to arrive
	 */
	public synchronized void updateStruct(HallCall call, Byte elevator, boolean isCompleted){
		byte tmpFloor = 0;
		byte tmpDirection = 0;
		synchronized(call){
			tmpFloor = call.getFloor();
			tmpDirection = call.getDirection();
		}
		
		if (tmpFloor != this.floor){
			return;
		}
		Globals.getLogger().log("Floor Event is compelete : " + isCompleted, this.getClass().getName(), "updateStruct");
		if (tmpDirection == ElevatorStruct.UP){
			isUpPressed = isCompleted;
			elevatorToService[ElevatorStruct.UP] = elevator;
		}else if(tmpDirection == ElevatorStruct.DOWN){
			isDownPressed = isCompleted;
			elevatorToService[ElevatorStruct.DOWN] = elevator;
		}
	}
	
	/**
	 * This method will update the struct using a HallCall object
	 * @param event The event made at the floor
	 */
	public synchronized void updateStruct(HallCallEvent event){
		byte tmpFloor = 0;
		boolean tmpIsComplete = false;
		synchronized(event){
			synchronized(event.getHallCall()){
				tmpFloor = event.getHallCall().getFloor();
			}
			tmpIsComplete = event.isRegistration();
		}
		
		if (tmpFloor != floor){
			return;
		}
		this.updateStruct(event.getHallCall(), floor, tmpIsComplete);
	}

	/**
	 * This method will return if the up button has been pressed
	 * @return Returns if the up button has been pressed
	 */
	public boolean isUpPressed() {
		return isUpPressed;
	}

	/**
	 * This method will return if the down button has been pressed
	 * @return Returns if the down button has been pressed
	 */
	public boolean isDownPressed() {
		return isDownPressed;
	}
	
}
